<?php
/**
*
* @package ppkBB3cker
* @version $Id: topdown_torrents_add1.php 1.000 2010-10-30 18:39:00 PPK $
* @copyright (c) 2010 PPK
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/

/**
* @ignore
*/
if (!defined('IN_PHPBB'))
{
	exit;
}

$dt=time();
$topdown_torrents='';
$ppkbb_postscr_fields=my_split_config($config['ppkbb_postscr_fields'], 2, 'strval');
$ppkbb_topdown_torrents_exclude=$r_torrents=$torrents_posters=$addfields_posters=$addfields_poster=$addfields_poster_thumb=array();
if($config['ppkbb_topdown_torrents_exclude'])
{
	$ppkbb_topdown_torrents_exclude=my_split_config($config['ppkbb_topdown_torrents_exclude'], 0, 'my_int_val', ',');
}
$disallow_access=array_unique(array_keys($auth->acl_getf('!f_read', true)));
if($config['ppkbb_topdown_torrents_trueexclude'])
{
	$ppkbb_topdown_torrents_exclude=array_unique(array_merge($ppkbb_topdown_torrents_exclude, $disallow_access));
	$disallow_access=array();
}

$sql="SELECT a.attach_id, a.post_msg_id, a.extension, a.real_filename, a.physical_filename, a.i_width, a.i_height, tt.topic_title, tt.topic_id, tt.forum_id, tt.topic_first_post_id, tt.topic_addfields_poster, t.times_completed, t.leechers, t.seeders, t.id torrent_id".($ppkbb_topdown_torrents[12]==3 || $ppkbb_topdown_torrents[13]==1 ? ', p.post_text, p.enable_smilies, p.enable_bbcode, p.enable_magic_url, p.bbcode_bitfield, p.bbcode_uid' : '')." FROM ".ATTACHMENTS_TABLE." a, ".TOPICS_TABLE." tt, ". TRACKER_TORRENTS_TABLE ." t".($ppkbb_topdown_torrents[12]==3 || $ppkbb_topdown_torrents[13]==1 ? ', '.POSTS_TABLE.' p' : '')." WHERE ".(sizeof($ppkbb_topdown_torrents_exclude) ? " tt.forum_id ".($config['ppkbb_topdown_torrents_trueexclude'] ? 'NOT '  : '')."IN('".implode("', '", $ppkbb_topdown_torrents_exclude)."') AND " : '').(sizeof($disallow_access) ? " tt.forum_id NOT IN('".implode("', '", $disallow_access)."') AND " : '').($topdown_torrents_fid ? " tt.forum_id='{$topdown_torrents_fid}' AND " : '')."a.post_msg_id=tt.topic_first_post_id AND tt.topic_id=t.topic_id ".($ppkbb_topdown_torrents[7] ? "AND t.seeders >= {$ppkbb_topdown_torrents[7]} " : '').($config['ppkbb_addfields_type'] && $ppkbb_postscr_fields[1] ? " AND ((a.i_poster='1'".($ppkbb_topdown_torrents[9] ? " AND a.thumbnail='1'" : '').") OR tt.topic_addfields_poster='1')" : " AND a.i_poster='1'".($ppkbb_topdown_torrents[9] ? " AND a.thumbnail='1'" : '')).($ppkbb_topdown_torrents[10] ? " AND t.added > ".($dt-($ppkbb_topdown_torrents[10]*86400)) : '').($ppkbb_topdown_torrents[12]==3 || $ppkbb_topdown_torrents[13]==1 ? ' AND p.post_id=tt.topic_first_post_id' : '')." GROUP BY tt.topic_id ORDER BY ".($ppkbb_topdown_torrents[11] ? 't.added' : 't.times_completed')." DESC LIMIT 0, {$ppkbb_topdown_torrents[3]}";

$result=$db->sql_query($sql, $ppkbb_topdown_torrents[6]*60);
while($row=$db->sql_fetchrow($result))
{
	$torrents_posters[$row['torrent_id']]=$row;
	$r_torrents[$row['torrent_id']]=$row['torrent_id'];
	$row['topic_addfields_poster'] ? $addfields_posters[$row['topic_first_post_id']]=$row['topic_first_post_id'] : '';
}
$db->sql_freeresult($result);

if($ppkbb_topdown_torrents[8] && sizeof($torrents_posters) < $ppkbb_topdown_torrents[8])
{
	$template->assign_vars(array(
		'TOPDOWN_TORRENTS_POSTERS' => false,
		)
	);
}
else
{
	$r_peers=array();
	if(!isset($ppkbb_tcenable_rannounces))
	{
		$ppkbb_tcenable_rannounces=my_split_config($config['ppkbb_tcenable_rannounces'], 9, 'my_int_val');
	}
	if($ppkbb_tcenable_rannounces[0] && sizeof($r_torrents))
	{
		$sql="SELECT torrent, SUM(seeders) seeders, SUM(leechers) leechers, SUM(peers) peers, SUM(times_completed) times_completed FROM ".TRACKER_RANNOUNCES_TABLE." WHERE torrent IN('".(implode("', '", $r_torrents))."') GROUP BY torrent";
		$result=$db->sql_query($sql, $ppkbb_topdown_torrents[6]*60);
		while($row=$db->sql_fetchrow($result))
		{
			$r_peers[$row['torrent']]=$row;
		}
		$db->sql_freeresult($result);
	}
	if(sizeof($addfields_posters))
	{
		$postscr_sql_addon=array();
		$ppkbb_postscr_fields=array_map('addslashes', $ppkbb_postscr_fields);
		$ppkbb_postscr_fields[1] ? $postscr_sql_addon[]=" field_name LIKE '{$ppkbb_postscr_fields[1]}%' OR field_name LIKE 'thumb\_{$ppkbb_postscr_fields[1]}%'" : '';
		$sql="SELECT * FROM ".TRACKER_ADDFIELDS_TABLE." WHERE post_msg_id IN('".implode("', '", $addfields_posters)."')".(sizeof($postscr_sql_addon) ? " AND (".implode(' OR ', $postscr_sql_addon).")" : '');
		$result=$db->sql_query($sql/*, $ppkbb_topdown_torrents[6]*60*/);
		while($row=$db->sql_fetchrow($result))
		{
			if(preg_match('/poster/i', $row['field_name']))
			{
				if(preg_match('/^thumb_/', $row['field_name']))
				{
					$addfields_poster_thumb[$row['post_msg_id']]=array($row['i_width'], $row['i_height'], $row['field_value']);
				}
				else
				{
					$addfields_poster[$row['post_msg_id']]=array($row['i_width'], $row['i_height'], $row['field_value']);
				}
			}
		}
		$db->sql_freeresult($result);

	}
	$sel_tdt=$tooltip_tdt='';
	$i=0;
	if($ppkbb_topdown_torrents[12]==3 || $ppkbb_topdown_torrents[13]==1)
	{
		$text_length=2000;
		include_once($phpbb_root_path . 'includes/bbcode.' . $phpEx);
		$bbcode = new bbcode();
	}
	foreach($torrents_posters as $k => $v)
	{
		if($ppkbb_topdown_torrents[12]==3 || $ppkbb_topdown_torrents[13]==1)
		{
			$message = $v['post_text'];

			// Parse the message and subject
			$message = censor_text($message);

			// Second parse bbcode here
			if ($v['bbcode_bitfield'])
			{
				$bbcode->bbcode_second_pass($message, $v['bbcode_uid'], $v['bbcode_bitfield']);
			}
			$message = bbcode_nl2br($message);
			$message = smiley_text($message);

			if ($text_length != 0 && (strlen($message) > $text_length))
			{
				$message = closetags(substr($message, 0, $text_length));
				$message .= '...';
			}

			$v['post_text']= $message;
		}
		//$i_factor=0.675;
		//$i_width=0;
		if(isset($addfields_poster[$v['topic_first_post_id']]))
		{
			if(isset($addfields_poster_thumb[$v['topic_first_post_id']][2]) && $ppkbb_topdown_torrents[9])
			{
				$i_factor=my_float_val($addfields_poster_thumb[$v['topic_first_post_id']][0]/$addfields_poster_thumb[$v['topic_first_post_id']][1]);
				$i_width=my_int_val($ppkbb_topdown_torrents[5]*$i_factor);
			}
			else
			{
				$i_factor=my_float_val($addfields_poster[$v['topic_first_post_id']][0]/$addfields_poster[$v['topic_first_post_id']][1]);
				$i_width=my_int_val($ppkbb_topdown_torrents[5]*$i_factor);
			}
		}
		else
		{
			$i_factor=my_float_val($v['i_width']/$v['i_height']);
			$i_width=my_int_val($ppkbb_topdown_torrents[5]*$i_factor);
		}
		$t_title=$v['topic_title']. " - {$user->lang['TORRENT_COMPLETED']}: ".($v['times_completed']+my_int_val(@$r_peers[$k]['times_completed']))." {$user->lang['TORRENT_SEEDERS']}: ".($v['seeders']+my_int_val(@$r_peers[$k]['seeders']))." {$user->lang['TORRENT_LEECHERS']}: ".($v['leechers']+my_int_val(@$r_peers[$k]['leechers']));
		$tdt_image=(isset($addfields_poster[$v['topic_first_post_id']]) ? '<img class="tdt_image" rel="tdt'.$i.'"'.($ppkbb_topdown_torrents[12]==3 || $ppkbb_topdown_torrents[13]==1 ? ' align="left" style="float:left;margin:5px;"' : '').' src="'.(isset($addfields_poster_thumb[$v['topic_first_post_id']][2]) && $ppkbb_topdown_torrents[9] ? $addfields_poster_thumb[$v['topic_first_post_id']][2] : $addfields_poster[$v['topic_first_post_id']][2]).'" alt="'.$t_title.'" height="'.($ppkbb_topdown_torrents[13]==2 ? '%d' : $ppkbb_topdown_torrents[5]).'" width="'.($ppkbb_topdown_torrents[13]==2 ? '%d' : $i_width).'" />' : '<img class="tdt_image" rel="tdt'.$i.'"'.($ppkbb_topdown_torrents[12]==3 || $ppkbb_topdown_torrents[13]==1 ? ' align="left" style="float:left;margin:5px;"' : '').' src="'.append_sid("{$phpbb_root_path}download/file.$phpEx", 'id=' . $v['attach_id']).($ppkbb_topdown_torrents[9] ? '&amp;t=1' : '').'" alt="'.$t_title.'" height="'.($ppkbb_topdown_torrents[13]==2 ? '%d' : $ppkbb_topdown_torrents[5]).'" width="'.($ppkbb_topdown_torrents[13]==2 ? '%d' : $i_width).'" />');
		$topdown_torrents.='<div class="panel"><a href="'.append_sid($phpbb_root_path.'viewtopic.' . $phpEx . '?t=' . $v['topic_id'] . '&amp;f=' . $v['forum_id']).'"'.($ppkbb_topdown_torrents[12]==3 || ($ppkbb_topdown_torrents[12]!=3 && !$ppkbb_topdown_torrents[13]) ? ' title = "'.$t_title.'"' : '').'>'.($ppkbb_topdown_torrents[13]==2 ? sprintf($tdt_image, $ppkbb_topdown_torrents[5], $i_width) : $tdt_image).'</a>'.($ppkbb_topdown_torrents[12]==3 ? $v['post_text'] : '').'</div>';
		if($ppkbb_topdown_torrents[12])
		{
			$sel_tdt.='<img style="cursor: pointer;" src="'.$phpbb_root_path.'tracker/addons/images/stepcarousel/opencircle.png" data-over="'.$phpbb_root_path.'tracker/addons/images/stepcarousel/graycircle.png" data-select="'.$phpbb_root_path.'tracker/addons/images/stepcarousel/opencircle.png" data-moveby="1" data-index="'.$i.'" data-moveto="'.$i.'" alt="" title="'.$v['topic_title'].'">'.($ppkbb_topdown_torrents[12]==1 ? ' &nbsp;' : '&nbsp;<a href="'.append_sid($phpbb_root_path.'viewtopic.' . $phpEx . '?t=' . $v['topic_id'] . '&amp;f=' . $v['forum_id']).'" title = "'.$t_title.'" >'.$v['topic_title'].'</a><br />');
		}
		if($ppkbb_topdown_torrents[13] && $ppkbb_topdown_torrents[12]!=3)
		{
			$tooltip_tdt.='<div style="display:none;" id="tdt'.$i.'">'.($ppkbb_topdown_torrents[13]==2 ? sprintf($tdt_image, $ppkbb_topdown_torrents[5]*2, $i_width*2) : $tdt_image).($ppkbb_topdown_torrents[13]==1 ? $v['post_text'] : '').'</div>';
		}
		$i+=1;
	}
	$tdt_count=sizeof($torrents_posters);
	$template->assign_vars(array(
		'TOPDOWN_TORRENTS_POSTERS' => $topdown_torrents ? $topdown_torrents : false,
		'TOPDOWN_TORRENTS_COUNT' => $tdt_count,
		'S_TOPDOWN_TORRENTS' => ($topdown_torrents_fid && @$forum_data['forum_name'] ? ($ppkbb_topdown_torrents[11] ? sprintf($user->lang['TOPDOWN_TORRENTS_ASNEWTORRENTS_INFORUM'], $tdt_count, $forum_data['forum_name']) : sprintf($user->lang['TOPDOWN_TORRENTS_INFORUM'], $tdt_count, $forum_data['forum_name'])) : ($ppkbb_topdown_torrents[11] ? sprintf($user->lang['TOPDOWN_TORRENTS_ASNEWTORRENTS'], $tdt_count) : sprintf($user->lang['TOPDOWN_TORRENTS'], $tdt_count))),
		'S_TOPDOWN_TORRENTS_WIDTH' => $ppkbb_topdown_torrents[4],
		'S_TOPDOWN_TORRENTS_WIDTH2' => $ppkbb_topdown_torrents[12]==3 ? $ppkbb_topdown_torrents[5]*2 : false,
		'S_TOPDOWN_TORRENTS_HEIGHT' => $ppkbb_topdown_torrents[5]+10,
		'S_TOPDOWN_TORRENTS_BUTTPOS' => my_int_val($ppkbb_topdown_torrents[5]/2),
		'S_SEL_TDT' => $ppkbb_topdown_torrents[12] ? $sel_tdt : false,
		'S_TDT_TYPE' => $ppkbb_topdown_torrents[12],
		'S_TDT_TOOLTIPS' => $tooltip_tdt ? $tooltip_tdt : false,
		)
	);
}

function closetags($text, $ex=array('area', 'base', 'basefont', 'br', 'col', 'frame', 'hr', 'img', 'input', 'isindex', 'link', 'meta', 'param'))
{
	$text = substr($text, 0, strrpos($text," "));
	$text = preg_replace("/<[^>]*$/i", "", $text);
	preg_match_all("/<[^a-z>\/]*([a-z]{1,50})/i", $text, $otags);
	if(count($otags[0])>0)
	{
		$fotags=$fctags=array();
		preg_match_all("/<[ t]*\/[^a-z]*([a-z]{1,50})/i", $text, $ctags);
		foreach($otags[1] as $otag)
		{
			$otag = strtolower($otag);
			if(isset($fotags[$otag]))
			{
				$fotags[$otag]++;
			}
			else
			{
				$fotags[$otag] = 1;
			}
		}
		foreach($ctags[1] as $ctag)
		{
			$ctag = strtolower($ctag);
			if(isset($fctags[$ctag]))
			{
				$fctags[$ctag]++;
			}
			else
			{
				$fctags[$ctag] = 1;
			}
		}
		while(list($tag, $cnt) = each($fotags))
		{
			if(in_array($tag, $ex))
			{
				continue;
			}
			$fctags[$tag] = isset($fctags[$tag]) ? $fctags[$tag] : 0;
			$text.=str_repeat("</$tag>", abs($fctags[$tag] - $cnt));
		}
	}
	return $text;
}
?>
